package com.spzx.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.constant.MqConstants;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.payment.config.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * Package: com.spzx.payment.service.impl
 *
 * @author xiongkunYang
 * @description:
 * @since 2025/6/9 14:19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class IAlipayServiceImpl implements IAlipayService {

    private final AlipayClient alipayClient;
    private final IPaymentInfoService paymentInfoService;
    private final RemoteOrderInfoService remoteOrderInfoService;
    private final RabbitService rabbitService;

    @SneakyThrows
    @Override
    public String submitAlipay(String orderNo) {

        // 创建API对应的request请求对象
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 同步回调
        alipayRequest.setReturnUrl(AlipayConfig.returnUrl);
        // 异步回调
        alipayRequest.setNotifyUrl(AlipayConfig.notifyUrl);

        /* 请求参数JSON集合 */
        JSONObject bizContent = new JSONObject();

        R<OrderInfo> orderInfoResult = this.remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
        if (R.FAIL == orderInfoResult.getCode()) {
            throw new ServiceException(orderInfoResult.getMsg());
        }
        OrderInfo orderInfo = orderInfoResult.getData();

        // 商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderNo);
        // 支付金额
        bizContent.put("total_amount", orderInfo.getTotalAmount());

        String content = orderInfo.getOrderItemList().stream()
                .map(OrderItem::getSkuName)
                // 使用逗号连接所有 SKU 名称
                .collect(Collectors.joining(","));
        // 订单标题，不可使用特殊符号
        bizContent.put("subject", content);
        // 手机网站支付默认传值QUICK_WAP_WAY(可选)
        bizContent.put("product_code", "QUICK_WAP_WAY");

        alipayRequest.setBizContent(bizContent.toString());
        // 默认请求方式为 POST
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayRequest);

        // 保存支付信息
        this.paymentInfoService.savePaymentInfo(orderInfo, content);

        // 调用SDK生成并返回表单
        return response.getBody();
    }

    @Override
    public void alipayNotify(Map<String, String> paramMap) {
        String outTradeNo = paramMap.get("out_trade_no");
        // 调用SDK验证签名
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    paramMap,
                    AlipayConfig.alipayPublicKey,
                    AlipayConfig.CHARSET,
                    AlipayConfig.SIGN_TYPE
            );
            // 校验验签是否成功
            if (!signVerified) {
                log.error("订单 {} 验签失败", outTradeNo);
            }
            log.error("订单 {} 验签成功", outTradeNo);
        } catch (AlipayApiException e) {
            log.error("验签失败", e);
        }

        // 交易状态
        String tradeStatus = paramMap.get("trade_status");
        if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {

            // 幂等性判断
            PaymentInfo paymentInfo = paymentInfoService.getOne(
                    new LambdaQueryWrapper<PaymentInfo>()
                            .eq(PaymentInfo::getOrderNo, outTradeNo)
                            .eq(PaymentInfo::getPayType, 2)
            );
            if (paymentInfo.getPaymentStatus() == 1) {
                return;
            }

            // 更新交易记录状态
            paymentInfoService.updatePaymentStatus(paymentInfo, paramMap);

            // 基于MQ通知订单模块修改订单状态
            this.rabbitService.sendMessage(MqConstants.EXCHANGE_PAYMENT_PAY, MqConstants.ROUTING_PAYMENT_PAY, outTradeNo);

            // 基于MQ通知商品模块扣减商品库存
            this.rabbitService.sendMessage(MqConstants.EXCHANGE_PRODUCT, MqConstants.ROUTING_MINUS, outTradeNo);


        }
    }
}